package com.demo2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;

// ========== 5. 机器ID工具类 ==========
class MachineIdUtil {
    public static String getCurrentMachineId() {
        try {
            String os = System.getProperty("os.name").toLowerCase();
            if (os.contains("win")) {
                return getWindowsMachineId();
            } else if (os.contains("mac")) {
                return getMacMachineId();
            } else {
                return getLinuxMachineId();
            }
        } catch (Exception e) {
            System.err.println("获取机器ID失败: " + e.getMessage());
            return "UNKNOWN_" + System.currentTimeMillis();
        }
    }
    
    private static String getWindowsMachineId() throws Exception {
        Process process = Runtime.getRuntime().exec("wmic csproduct get UUID");
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (line.length() > 10 && line.contains("-")) {
                return "WIN_" + line;
            }
        }
        return "WIN_FALLBACK_" + System.getProperty("user.name");
    }
    
    private static String getMacMachineId() throws Exception {
        Process process = Runtime.getRuntime().exec("system_profiler SPHardwareDataType");
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.contains("Hardware UUID:")) {
                return "MAC_" + line.split(":")[1].trim();
            }
        }
        return "MAC_FALLBACK_" + System.getProperty("user.name");
    }
    
    private static String getLinuxMachineId() throws Exception {
        // 优先使用/etc/machine-id
        File machineIdFile = new File("/etc/machine-id");
        if (machineIdFile.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(machineIdFile))) {
                String machineId = reader.readLine();
                if (machineId != null && !machineId.trim().isEmpty()) {
                    return "LINUX_" + machineId.trim();
                }
            }
        }
        
        // 备用方案：使用hostname
        Process process = Runtime.getRuntime().exec("hostname");
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String hostname = reader.readLine();
        return "LINUX_" + (hostname != null ? hostname.trim() : "UNKNOWN");
    }
}
